package com.fwmagic.springcloud.controller;

import com.fwmagic.springcloud.entities.CommonResult;
import com.fwmagic.springcloud.entities.Payment;
import com.fwmagic.springcloud.lb.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

@RestController
@Slf4j
public class OrderController {

    //public static final String PAYMENT_SERVICE_URL = "http://localhost:8001";
    public static final String PAYMENT_SERVICE_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Autowired
    private RestTemplate restTemplate;

    @Resource
    private LoadBalancer loadBalancer;

    //可以获取注册中心上的服务列表
    @Resource
    private DiscoveryClient discoveryClient;

    /**
     * 客户端用浏览器是get请求，但底层实际发送的是post调用服务8001
     *
     * @param payment
     * @return
     */
    @GetMapping("/consumer/payment/create")
    public CommonResult create(Payment payment) {
        log.info("****** consumer/payment/create,request:{} ******", payment);
        return restTemplate.postForObject(PAYMENT_SERVICE_URL + "/payment/create", payment, CommonResult.class);
    }

    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult get(@PathVariable("id") Long id) {
        log.info("****** /consumer/payment/get/{},id:{} ******", id, id);
        return restTemplate.getForObject(PAYMENT_SERVICE_URL + "/payment/get/" + id, CommonResult.class);
    }


    @GetMapping("/consumer/payment/lb")
    public String getPaymentLb() {
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if (instances == null || instances.size() == 0) {
            return null;
        }
        ServiceInstance serviceInstance = loadBalancer.instances(instances);
        URI uri = serviceInstance.getUri();
        System.out.println("******uri:" + uri);
        return restTemplate.getForObject(uri + "/payment/lb", String.class);
    }


    @GetMapping("/consumer/payment/l2")
    public String getPaymentLb2() {
        return "aaa";
    }

    @GetMapping("/consumer/payment/zipkin")
    public String getPaymentZipkin() {
        String result = restTemplate.getForObject(PAYMENT_SERVICE_URL + "/payment/zipkin", String.class);
        return result;
    }

}
